from __future__ import annotations

import json
import os
import uuid
from typing import Any, Dict, List, Optional


class SessionStore:
    """Simple JSON-backed session store.

    Schema:
    {
      "sessions": [
        {"id": "uuid", "name": "...", "type": "ssh", "params": {"host": "...", "port": 22, "user": "...", "password": ""}},
        {"id": "uuid", "name": "...", "type": "serial", "params": {"port": "COM3", "baud": 115200}}
      ]
    }
    """

    def __init__(self, file_path: str) -> None:
        self.file_path = file_path
        self._data: Dict[str, Any] = {"sessions": []}
        self.load()

    def load(self) -> None:
        try:
            if os.path.exists(self.file_path):
                with open(self.file_path, "r", encoding="utf-8") as f:
                    self._data = json.load(f)
            else:
                self._data = {"sessions": []}
        except Exception:
            self._data = {"sessions": []}

    def save(self) -> None:
        folder = os.path.dirname(self.file_path)
        if folder and not os.path.exists(folder):
            os.makedirs(folder, exist_ok=True)
        with open(self.file_path, "w", encoding="utf-8") as f:
            json.dump(self._data, f, ensure_ascii=False, indent=2)

    def list(self) -> List[Dict[str, Any]]:
        return list(self._data.get("sessions", []))

    def add(self, name: str, sess_type: str, params: Dict[str, Any]) -> Dict[str, Any]:
        item = {"id": str(uuid.uuid4()), "name": name, "type": sess_type, "params": params}
        self._data.setdefault("sessions", []).append(item)
        self.save()
        return item

    def update(self, sess_id: str, **fields: Any) -> Optional[Dict[str, Any]]:
        for s in self._data.get("sessions", []):
            if s.get("id") == sess_id:
                s.update(fields)
                self.save()
                return s
        return None

    def delete(self, sess_id: str) -> bool:
        arr = self._data.get("sessions", [])
        for i, s in enumerate(arr):
            if s.get("id") == sess_id:
                del arr[i]
                self.save()
                return True
        return False

    def get(self, sess_id: str) -> Optional[Dict[str, Any]]:
        for s in self._data.get("sessions", []):
            if s.get("id") == sess_id:
                return s
        return None
